<template>
  <div class="login-container" :class="{ 'dark-mode': isDarkMode }">
    <!-- 主题切换按钮 -->
    <div class="theme-toggle">
      <el-tooltip :content="isDarkMode ? '切换到浅色模式' : '切换到深色模式'" placement="left">
        <el-button 
          type="text" 
          class="theme-toggle-btn" 
          @click="toggleTheme"
        >
          <el-icon><component :is="themeIcon" /></el-icon>
        </el-button>
      </el-tooltip>
    </div>
    <!-- 背景装饰 -->
    <div class="login-bg">
      <div class="bg-decoration">
        <div class="decoration-circle circle-1"></div>
        <div class="decoration-circle circle-2"></div>
        <div class="decoration-circle circle-3"></div>
        <div class="decoration-wave"></div>
      </div>
    </div>

    <!-- 登录面板 -->
    <div class="login-panel animate-fadeIn">
      <!-- 系统Logo和标题 -->
      <div class="login-header">
        <div class="logo-container">
          <div class="logo-icon">
            <el-icon size="48"><School /></el-icon>
          </div>
          <div class="logo-text">
            <h1 class="system-title">综合测评系统</h1>
            <p class="system-subtitle">
              University Comprehensive Evaluation System
            </p>
          </div>
        </div>
      </div>

      <!-- 欢迎信息 -->
      <div class="welcome-section">
        <h2 class="welcome-title">欢迎回来</h2>
        <p class="welcome-desc">请登录您的账户以继续使用系统</p>
      </div>

      <!-- 登录表单 -->
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        label-position="top"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="username" label="学号/工号" class="form-item-enhanced">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入学号/工号 (数字或字母组合)"
            clearable
            autofocus
            size="large"
            class="input-enhanced"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
          <div class="form-help-text">
            <small>测试账号: 10001(管理员), 10002(学生), 10003(辅导员)</small>
          </div>
        </el-form-item>

        <el-form-item prop="password" label="密码" class="form-item-enhanced">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码 (至少6位)"
            clearable
            show-password
            size="large"
            class="input-enhanced"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
          <div class="form-help-text">
            <small>测试密码: 123456</small>
          </div>
        </el-form-item>

        <el-form-item prop="role" label="角色" class="form-item-enhanced">
          <el-select
            v-model="loginForm.role"
            placeholder="请选择您的角色"
            size="large"
            style="width: 100%"
            class="select-enhanced"
          >
            <el-option label="👨‍🎓 学生" value="student">
              <span class="role-option">
                <el-icon><User /></el-icon>
                <span>学生</span>
              </span>
            </el-option>
            <el-option label="👨‍💼 管理员" value="admin">
              <span class="role-option">
                <el-icon><UserFilled /></el-icon>
                <span>管理员</span>
              </span>
            </el-option>
            <el-option label="👨‍💻 领导" value="leader">
              <span class="role-option">
                <el-icon><Star /></el-icon>
                <span>领导</span>
              </span>
            </el-option>
          </el-select>
        </el-form-item>

        <div class="form-options">
          <el-checkbox v-model="loginForm.remember" class="remember-checkbox">
            记住我
          </el-checkbox>
          <el-link
            type="primary"
            @click.prevent="handleForgotPassword"
            class="forgot-link"
          >
            忘记密码？
          </el-link>
        </div>

        <el-form-item class="login-button-item">
          <el-button
            type="primary"
            class="login-btn btn-gradient"
            :loading="loading"
            @click="handleLogin"
            :disabled="loading"
            size="large"
          >
            <span v-if="!loading">
              <el-icon><Right /></el-icon>
              立即登录
            </span>
            <span v-else>
              <el-icon class="animate-spin"><Loading /></el-icon>
              登录中...
            </span>
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 页脚信息 -->
      <div class="login-footer">
        <div class="footer-links">
          <el-link type="info" class="footer-link">使用帮助</el-link>
          <span class="divider">|</span>
          <el-link type="info" class="footer-link">联系我们</el-link>
          <span class="divider">|</span>
          <el-link type="info" class="footer-link">隐私政策</el-link>
        </div>
        <div class="copyright">© 2025 大学生综合测评系统 版权所有</div>
      </div>
    </div>

    <!-- 侧边装饰信息 -->
    <div class="side-info animate-slideInRight">
      <div class="info-card glass-effect">
        <h3>系统特色</h3>
        <ul class="feature-list">
          <li>
            <el-icon><Check /></el-icon> 智能化测评流程
          </li>
          <li>
            <el-icon><Check /></el-icon> 多维度数据分析
          </li>
          <li>
            <el-icon><Check /></el-icon> 实时成绩查询
          </li>
          <li>
            <el-icon><Check /></el-icon> 便捷申诉处理
          </li>
        </ul>
      </div>

      <div class="stats-card glass-effect">
        <div class="stat-item">
          <div class="stat-number">1000+</div>
          <div class="stat-label">活跃用户</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">50+</div>
          <div class="stat-label">测评项目</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">99.9%</div>
          <div class="stat-label">系统稳定性</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
// [MODIFIED] 使用绝对不会出错的相对路径
import { useUserStore, useThemeStore } from "../store/index.js";
import { ElMessage } from "element-plus";
import { userAPI } from "../api/user.js";
// 图标已全局注册，无需单独导入

const router = useRouter();
const userStore = useUserStore();
const themeStore = useThemeStore();
const loginFormRef = ref(null);

// 主题相关计算属性
const isDarkMode = computed(() => themeStore.isDark);
const themeIcon = computed(() => themeStore.themeIcon);

// 主题切换方法
const toggleTheme = () => {
  themeStore.toggleTheme();
};


const loginForm = reactive({
  username: "",
  password: "",
  role: "",
  remember: false,
});

const loginRules = {
  username: [
    { required: true, message: "请输入学号/工号", trigger: "blur" },
    { min: 5, max: 20, message: "学号/工号长度应在5-20个字符之间", trigger: "blur" },
    { pattern: /^[a-zA-Z0-9_]+$/, message: "学号/工号只能包含字母、数字和下划线", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  role: [{ required: true, message: "请选择您的角色", trigger: "change" }],
};

const loading = ref(false);

const handleLogin = () => {
  if (!loginFormRef.value) return;

  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const loginData = {
          username: loginForm.username.trim(),
          password: loginForm.password,
        };

        const loginResult = await userAPI.login(loginData);
        ElMessage.success("登录成功！");
        userStore.login(loginResult);

        if (loginForm.remember) {
          localStorage.setItem(
            "loginForm",
            JSON.stringify({
              username: loginForm.username,
              role: loginForm.role,
              remember: true,
            })
          );
        } else {
          localStorage.removeItem("loginForm");
        }

        const userRealRoleId = userStore.getRoleId;
        const roleMap = { admin: 1, student: 2, leader: 3 };

        if (roleMap[loginForm.role] !== userRealRoleId) {
          ElMessage.error("您选择的角色与账号实际角色不符！");
          userStore.logout();
          return;
        }

        switch (userRealRoleId) {
          case 1:
            router.push("/admin/dashboard");
            break;
          case 2:
            router.push("/student/dashboard");
            break;
          case 3:
            router.push("/leader/dashboard");
            break;
          default:
            ElMessage.warning("角色未知，无法跳转");
            router.push("/");
        }
      } catch (error) {
        console.error("登录流程失败:", error);

        // 详细的错误处理
        if (error.response) {
          const status = error.response.status;
          const message =
            error.response.data?.message ||
            error.response.data?.error ||
            "登录失败";

          switch (status) {
            case 401:
              ElMessage.error("学号/工号或密码错误，请检查后重试");
              break;
            case 403:
              ElMessage.error("账号已被禁用，请联系管理员");
              break;
            case 404:
              ElMessage.error("学号/工号不存在，请检查输入");
              break;
            case 429:
              ElMessage.error("登录尝试过于频繁，请稍后再试");
              break;
            case 500:
              ElMessage.error("服务器内部错误，请稍后重试或联系管理员");
              break;
            default:
              ElMessage.error(`登录失败: ${message}`);
          }
        } else if (error.request) {
          ElMessage.error("网络连接失败，请检查网络连接后重试");
        } else {
          ElMessage.error("登录过程中发生未知错误，请重试");
        }
      } finally {
        loading.value = false;
      }
    } else {
      ElMessage.error("请检查输入项是否完整");
      return false;
    }
  });
};

const handleForgotPassword = () => {
  ElMessage.info("忘记密码功能即将上线，请联系管理员重置密码");
};

const initLoginForm = () => {
  try {
    const savedForm = localStorage.getItem("loginForm");
    if (savedForm) {
      const parsedForm = JSON.parse(savedForm);
      if (parsedForm.remember) {
        loginForm.username = parsedForm.username || "";
        loginForm.role = parsedForm.role || "";
        loginForm.remember = true;
      }
    }
  } catch (error) {
    console.error("读取记住的登录信息失败:", error);
  }
};

onMounted(() => {
  initLoginForm();
});
</script>

<style scoped>
/* ===== 登录页面样式 ===== */

.login-container {
  min-height: 100vh;
  width: 100vw;
  display: flex;
  position: relative;
  overflow: hidden;
  transition: all var(--transition-base);
}

/* 主题切换按钮 */
.theme-toggle {
  position: fixed;
  top: 24px;
  right: 24px;
  z-index: 1000;
}

.theme-toggle-btn {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  font-size: 20px;
  transition: all var(--transition-base);
  display: flex;
  align-items: center;
  justify-content: center;
}

.theme-toggle-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
  box-shadow: var(--shadow-base);
}

/* 深色模式下的主题按钮 */
.dark-mode .theme-toggle-btn {
  background: rgba(0, 0, 0, 0.3);
  border-color: rgba(255, 255, 255, 0.2);
}

.dark-mode .theme-toggle-btn:hover {
  background: rgba(0, 0, 0, 0.5);
}

/* 背景样式 */
.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  z-index: 1;
}

.bg-decoration {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.decoration-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  animation: float 6s ease-in-out infinite;
}

.circle-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.circle-2 {
  width: 150px;
  height: 150px;
  top: 60%;
  left: 80%;
  animation-delay: 2s;
}

.circle-3 {
  width: 100px;
  height: 100px;
  top: 80%;
  left: 20%;
  animation-delay: 4s;
}

.decoration-wave {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100px;
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1200 120'%3E%3Cpath d='M321.39,56.44c58-10.79,114.16-30.13,172-41.86,82.39-16.72,168.19-17.73,250.45-.39C823.78,31,906.67,72,985.66,92.83c70.05,18.48,146.53,26.09,214.34,3V0H0V27.35A600.21,600.21,0,0,0,321.39,56.44Z' fill='rgba(255,255,255,0.1)'%3E%3C/path%3E%3C/svg%3E")
    repeat-x;
  animation: wave 10s linear infinite;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

@keyframes wave {
  0% {
    background-position-x: 0;
  }
  100% {
    background-position-x: 1200px;
  }
}

/* 登录面板样式 */
.login-panel {
  position: relative;
  z-index: 10;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 48px;
  width: 100%;
  max-width: 480px;
  margin: auto;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

/* Logo和标题区域 */
.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.logo-icon {
  width: 80px;
  height: 80px;
  background: var(--primary-gradient);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.3);
  animation: logoGlow 2s ease-in-out infinite alternate;
}

@keyframes logoGlow {
  0% {
    box-shadow: 0 8px 24px rgba(64, 158, 255, 0.3);
  }
  100% {
    box-shadow: 0 12px 32px rgba(64, 158, 255, 0.5);
  }
}

.logo-text {
  text-align: center;
}

.system-title {
  font-size: 28px;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 8px 0;
  background: var(--primary-gradient);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.system-subtitle {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0;
  font-weight: 400;
}

/* 欢迎区域 */
.welcome-section {
  text-align: center;
  margin-bottom: 32px;
}

.welcome-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 8px 0;
}

.welcome-desc {
  font-size: 16px;
  color: var(--text-regular);
  margin: 0;
}

/* 表单样式 */
.login-form {
  width: 100%;
}

.form-item-enhanced {
  margin-bottom: 24px;
}

.form-item-enhanced :deep(.el-form-item__label) {
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.form-help-text {
  margin-top: 4px;
  padding-left: 4px;
}

.form-help-text small {
  color: var(--text-secondary);
  font-size: 12px;
  opacity: 0.8;
}

.input-enhanced :deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid var(--border-light);
  transition: all var(--transition-base);
}

.input-enhanced :deep(.el-input__wrapper:hover) {
  border-color: var(--primary-color);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

.input-enhanced :deep(.el-input__wrapper.is-focus) {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.select-enhanced :deep(.el-select__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid var(--border-light);
  transition: all var(--transition-base);
}

.role-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 表单选项 */
.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}

.remember-checkbox :deep(.el-checkbox__label) {
  color: var(--text-regular);
  font-weight: 500;
}

.forgot-link {
  font-weight: 500;
  text-decoration: none;
}

.forgot-link:hover {
  text-decoration: underline;
}

/* 登录按钮 */
.login-button-item {
  margin-bottom: 0;
}

.login-btn {
  width: 100%;
  height: 48px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  border: none;
  position: relative;
  overflow: hidden;
}

.login-btn:before {
  content: "";
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(255, 255, 255, 0.2),
    transparent
  );
  transition: left 0.5s;
}

.login-btn:hover:before {
  left: 100%;
}

/* 页脚样式 */
.login-footer {
  margin-top: 32px;
  text-align: center;
}

.footer-links {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.footer-link {
  font-size: 14px;
  color: var(--text-secondary);
  text-decoration: none;
}

.footer-link:hover {
  color: var(--primary-color);
}

.divider {
  color: var(--text-placeholder);
  font-size: 12px;
}

.copyright {
  font-size: 12px;
  color: var(--text-placeholder);
}

/* 侧边信息区域 */
.side-info {
  position: absolute;
  right: 80px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
  display: flex;
  flex-direction: column;
  gap: 24px;
  width: 300px;
}

.info-card,
.stats-card {
  padding: 24px;
  border-radius: 16px;
  color: white;
}

.info-card h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
}

.feature-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.feature-list li {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-size: 14px;
}

.feature-list li:last-child {
  margin-bottom: 0;
}

.stats-card {
  display: flex;
  justify-content: space-between;
  text-align: center;
}

.stat-item {
  flex: 1;
}

.stat-number {
  font-size: 20px;
  font-weight: 700;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  opacity: 0.8;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .side-info {
    display: none;
  }

  .login-container {
    justify-content: center;
    align-items: center;
    padding: 20px;
  }
}

@media (max-width: 768px) {
  .login-panel {
    padding: 32px 24px;
    margin: 20px;
    max-width: none;
  }

  .system-title {
    font-size: 24px;
  }

  .welcome-title {
    font-size: 20px;
  }

  .logo-icon {
    width: 60px;
    height: 60px;
  }

  .logo-icon :deep(.el-icon) {
    font-size: 32px;
  }
}

@media (max-width: 480px) {
  .login-panel {
    padding: 24px 16px;
    border-radius: 16px;
  }

  .form-options {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
}
</style>
